<template>
  <el-config-provider :locale="appStore.locale" :size="(appStore.size as any)">
    <div class="p-5">
      <!-- 查询条件 -->
      <div class="query-condition flex justify-between">
        <div class="condition">
          <el-input class="w-50 mr-3" v-model="searchInfo.tableName" placeholder="表名"></el-input>
          <el-input class="w-50 mr-3" v-model="searchInfo.tableDesc" placeholder="表注释"></el-input>
          <el-button type="primary" plain @click="reloadTable">
            <i-ep-Refresh />
          </el-button>
          <el-button type="primary" @click="init">
            <i-ep-Search />
          </el-button>
        </div>
        <div class="button">
          <el-select
            @change="reloadTable(), loadAllTableInfo()"
            v-model="searchInfo.dbId"
            placeholder="请选择数据源"
            class="mr-3"
          >
            <el-option
              v-for="item in dbSelect"
              :key="item.id"
              :label="item.dbName"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button type="primary" @click="createTable" :disabled="searchInfo.dbId ? false : true">
            <i-ep-CirclePlusFilled class="mr-2" />
            新建表
          </el-button>
        </div>
      </div>

      <!-- 表格展示 -->
      <div class="table-content mt-5">
        <el-table :data="tableData" border :cell-style="cellStyle" style="width: 100%">
          <el-table-column align="center" type="index" width="60" label="序号"></el-table-column>
          <el-table-column
            align="center"
            prop="tableName"
            show-overflow-tooltip
            label="表名"
            width="300"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="tableDesc"
            show-overflow-tooltip
            label="表注释"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="menuName"
            show-overflow-tooltip
            label="适用模块"
          ></el-table-column>
          <el-table-column align="center" prop="prop" label="操作" width="200">
            <template #default="{ row }">
              <el-button plain type="primary" size="small" @click="openFieldInfo(row)">
                字段信息
              </el-button>
              <el-button plain type="primary" size="small" @click="editBindMenuInfo(row)">
                适用模块
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="mt-4">
        <el-pagination
          v-model:current-page="searchInfo.page"
          v-model:page-size="searchInfo.limit"
          background
          layout="prev, pager, next, jumper, total"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新建表 -->
    <el-dialog title="新建表" width="800" v-model="showDialog" :close-on-click-modal="false">
      <div class="p-5 pt-0">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          inline
          label-width="100px"
          label-position="left"
        >
          <el-form-item class="w-47%" label="表名" prop="tableName">
            <el-input
              @blur="validateTableNameEn"
              v-model="ruleForm.tableName"
              placeholder="请输入表名"
            ></el-input>
          </el-form-item>
          <el-form-item class="w-47%" label="表注释" prop="tableDesc">
            <el-input v-model="ruleForm.tableDesc" placeholder="请输入表注释"></el-input>
          </el-form-item>
          <el-form-item class="w-47%" label="主键字段名" prop="tableFieldName">
            <el-input
              disabled
              @blur="validateFieldNameEn"
              v-model="ruleForm.tableFieldName"
              placeholder="请输入主键字段名"
            ></el-input>
          </el-form-item>
          <el-form-item class="w-47%" label="字段注释" prop="tableFieldDesc">
            <el-input v-model="ruleForm.tableFieldDesc" placeholder="请输入字段注释"></el-input>
          </el-form-item>
          <el-form-item class="w-47%" label="字段类型" prop="fieldType">
            <el-select v-model="ruleForm.fieldType" placeholder="请选择字段类型" class="w-full">
              <el-option
                v-for="item in fieldTypeSelect"
                :key="item.typeName"
                :label="item.typeName"
                :value="item.typeName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="w-47%" label="长度" prop="fieldLength">
            <el-input v-model="ruleForm.fieldLength" placeholder="请输入长度"></el-input>
          </el-form-item>
          <el-form-item class="w-47%" label="默认值" prop="fieldValue">
            <el-select v-model="ruleForm.fieldValue" placeholder="请选择默认值" class="w-full">
              <el-option
                v-for="item in [{ value: '2', label: '不为空' }]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="w-47%" label="适用模块" prop="menuId">
            <el-tree-select
              placeholder="请选择适用模块"
              v-loading="loadingMenu"
              class="w-full"
              v-model="ruleForm.menuId"
              :data="menuTreeSelect"
              node-key="rightId"
              :props="{
                label: 'rightName',
                children: 'children'
              }"
              :render-after-expand="false"
            ></el-tree-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="flex justify-end">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button :loading="loadingBtn" type="primary" @click="submit(ruleFormRef)">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 字段信息 -->
    <el-dialog title="字段信息" width="800" v-model="showDialogFieldInfo" :close-on-click-modal="false">
      <div class="pb-5 flex flex-col">
        <div>
          <el-button type="primary" @click="addField">添加字段</el-button>
          <el-button :disabled="selectTableField.length === 0" plain type="primary" @click="copyField">
            <i-ep-CopyDocument class="mr-1" />
            复制
          </el-button>
          <el-button :disabled="copyItems.length === 0" plain type="primary" @click="pasteField">
            <i-ep-FolderChecked class="mr-1" />
            粘贴
          </el-button>
        </div>
        <div class="table-content mt-5">
          <el-table
            :cell-style="cellStyle"
            default-expand-all
            row-key="id"
            border
            :data="fieldTable"
            @selection-change="handleSelectionChange"
            style="width: 100%"
          >
            <el-table-column align="center" type="selection" width="50" />
            <el-table-column
              show-overflow-tooltip
              align="center"
              prop="fieldName"
              label="字段名称"
            ></el-table-column>
            <el-table-column
              align="center"
              show-overflow-tooltip
              prop="fieldType"
              label="类型"
            ></el-table-column>
            <el-table-column align="center" prop="notNull" label="是否必填" width="90">
              <template #default="{ row }">
                <span>{{ row.notNull === '-' || row.notNull === '非必填' ? '非必填' : '必填' }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="notSelect" label="可选择层级"></el-table-column>
            <el-table-column align="center" prop="prop" label="操作">
              <template #default="{ row }">
                <el-button @click="removeField(row)" size="small" type="danger" plain>删除</el-button>
                <el-button @click="editField(row)" size="small" type="primary" plain>编辑</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="mt-4">
            <el-pagination
              v-model:current-page="searchInfoField.page"
              v-model:page-size="searchInfoField.limit"
              background
              layout="prev, pager, next, jumper, total"
              :total="totalField"
              @current-change="handleFieldCurrentChange"
            />
          </div>
        </div>
      </div>
      <div slot="footer" class="flex justify-end">
        <el-button type="primary" @click="showDialogFieldInfo = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加字段 -->
    <el-dialog v-model="showAddField" title="添加字段" width="700" :close-on-click-modal="false">
      <div class="flex-center">
        <el-transfer
          v-loading="loadingField"
          filterable
          v-model="selectedField"
          :filter-method="filterMethod"
          filter-placeholder="名称搜索"
          :titles="['全部字段', '已选字段']"
          :props="{
            key: 'id',
            label: 'fieldName'
          }"
          :data="fieldSelect"
        >
          <template #default="{ option }">
            <span>{{ option.fieldName }}</span>
            <span class="text-3 text-gray ml-2">({{ option.fieldType }})</span>
          </template>
        </el-transfer>
      </div>
      <div slot="footer" class="flex justify-center mt-10">
        <el-button
          :loading="loadingBtn"
          :disabled="selectedField.length === 0"
          type="primary"
          @click="sureAddField(false)"
        >
          保 存
        </el-button>
      </div>
    </el-dialog>

    <!-- 编辑字段 -->
    <el-dialog v-model="showEditField" title="编辑字段" width="500" :close-on-click-modal="false">
      <div class="p-5 pb-0">
        <el-form label-position="left" label-width="80px">
          <el-form-item label="字段名称">
            <el-input v-model="currentFieldRow.fieldName" disabled placeholder="字段名称"></el-input>
          </el-form-item>
          <el-form-item label="字段类型">
            <el-input v-model="currentFieldRow.fieldType" disabled placeholder="字段类型"></el-input>
          </el-form-item>
          <el-form-item label="是否必填">
            <el-radio-group v-model="currentFieldRow.notNull">
              <el-radio label="必填">必填</el-radio>
              <el-radio label="非必填">非必填</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="可选选项" v-if="currentFieldRow.fieldType === '下拉框'">
            <el-radio-group v-model="currentFieldRow.notSelect">
              <el-radio label="可选任意层级">可选任意层级</el-radio>
              <el-radio label="只能选末级">只能选末级</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="flex justify-end mt-5">
        <el-button type="primary" @click="showEditField = false" plain>取 消</el-button>
        <el-button :loading="loadingBtn" type="primary" @click="sureEditField">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改绑定的适用模块 -->
    <el-dialog
      title="修改绑定的适用模块"
      v-model="showBindMenu"
      width="380"
      :close-on-click-modal="false"
    >
      <div class="p-5">
        <el-tree-select
          placeholder="请选择适用模块"
          v-loading="loadingMenu"
          class="w-full"
          v-model="currentMenuId"
          :data="menuTreeSelect"
          node-key="rightId"
          :props="{
            label: 'rightName',
            children: 'children'
          }"
          :render-after-expand="false"
        ></el-tree-select>
      </div>
      <div slot="footer" class="flex-center mt-5">
        <el-button @click="showBindMenu = false">取 消</el-button>
        <el-button type="primary" :loading="loadingBtn" @click="sureChangeMenu">确 定</el-button>
      </div>
    </el-dialog>
  </el-config-provider>
</template>

<script setup lang="ts">
//@ts-nocheck
import { useQueryTable } from '@/utils/hooks/useQueryTable';
import { useAppStore } from '@/store/modules/app';
import type { FormInstance, FormRules, TransferDataItem } from 'element-plus';
import XyTools from '@/utils/functions/xy-tools';
import {
  ledgerTableTabApi,
  dbInfoListApi,
  ledgerTableFormApi,
  fieldTypeListApi,
  loadMenuApi,
  addTableApi,
  ledgerTableFieldTabApi,
  addFiledApi,
  ledgerTableFieldFormApi,
  ledgerTableFieldFormListApi,
  deleteFiledApi,
  ledgerTableFieldDelApi
} from '@/utils/api/createTable';
import { ledgerFieldTabApi } from '@/utils/api/createField';
import { json } from 'stream/consumers';

const appStore = useAppStore();
const $xy = new XyTools();
const showDialog = ref(false);
const showDialogFieldInfo = ref(false);
const showBindMenu = ref(false);
const showAddField = ref(false);
const showEditField = ref(false);
const dbSelect = ref([]); // 数据库下拉
const fieldTypeSelect = ref([]); // 字段类型下拉
const menuTreeSelect = ref([]); // 选择菜单模块树形下拉
const allTableInfo = ref([]);
const menuList = ref([]); // 全部菜单模块
const fieldSelect = ref([]); // 所有字段穿梭项
const selectedField = ref([]); // 已选字段
const copyItems = ref([]); // 已经复制字段
const selectTableField = ref([]); // 已选可复制字段
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<any>({
  dbId: '',
  dbName: '',
  tableName: '',
  tableDesc: '',
  tableFieldName: 'ID',
  tableFieldDesc: 'ID',
  fieldType: 'VARCHAR',
  fieldLength: '50',
  fieldValue: '2',
  menuId: ''
});
const rules = reactive<FormRules<any>>({
  tableName: [{ required: true, message: '必填项', trigger: 'blur' }],
  tableDesc: [{ required: true, message: '必填项', trigger: 'blur' }],
  tableFieldName: [{ required: true, message: '必填项', trigger: 'blur' }],
  tableFieldDesc: [{ required: true, message: '必填项', trigger: 'blur' }],
  fieldType: [{ required: true, message: '必填项', trigger: 'blur' }],
  fieldLength: [{ required: true, message: '必填项', trigger: 'blur' }],
  fieldValue: [{ required: true, message: '必填项', trigger: 'blur' }],
  menuId: [{ required: true, message: '必填项', trigger: 'blur' }]
});
const loadingMenu = ref(false);
const loadingField = ref(false);
const searchInfoField = reactive({
  page: 1,
  limit: 10,
  tableId: ''
});
const fieldTable = ref([]);
const fieldTableAll = ref([]);
const totalField = ref(0);
const currentMenuId = ref(null);

let currentRow = null;
let currentFieldRow = ref(null);

// 初始化
const init = async () => {
  loading.value = true;
  const res = await ledgerTableTabApi(searchInfo);
  loading.value = false;

  if (res.status === 200) {
    tableData.value = res.data;
    total.value = Number(res.count);
  } else {
    ElMessage.error(res.msg);
  }
};

// 重新加载表格
const reloadTable = (type = 1) => {
  searchInfo.tableName = '';
  searchInfo.tableDesc = '';
  type && (searchInfo.page = 1);
  searchInfo.limit = 10;
  init();
};

const {
  tableData,
  searchInfo,
  total,
  loading,
  loadingBtn,
  handleSizeChange,
  handleCurrentChange,
  cellStyle
} = useQueryTable(init);

// 新建表
const createTable = () => {
  loadingBtn.value = false;
  showDialog.value = true;
  ruleForm.tableName = '';
  ruleForm.tableDesc = '';
  ruleForm.menuId = '';
};

const validateTableNameEn = () => {
  ruleForm.tableName = ruleForm.tableName.toUpperCase();

  ruleForm.tableName = ruleForm.tableName.replace(/[^A-Z_]/g, '');

  const repeat = allTableInfo.value.find((item) => item.tableName === ruleForm.tableName);

  if (repeat) {
    ruleForm.tableName = '';
    ElMessage.error('表名重复');
  }
};

const validateFieldNameEn = () => {
  ruleForm.tableFieldName = ruleForm.tableFieldName.toUpperCase();

  ruleForm.tableFieldName = ruleForm.tableFieldName.replace(/[^A-Z_]/g, '');
};

// 打开字段信息弹窗
const openFieldInfo = async (row) => {
  currentRow = row;
  showDialogFieldInfo.value = true;
  searchInfoField.tableId = row.id;
  loadingBtn.value = false;
  initFieldTable();
  queryAllFieldTable();
};

// 修改绑定的菜单信息
const editBindMenuInfo = (row) => {
  showBindMenu.value = true;
  currentMenuId.value = null;
  loadingBtn.value = false;
  currentRow = row;
};

// 初始化字段表
const initFieldTable = async () => {
  const res = await ledgerTableFieldTabApi(searchInfoField);

  if (res.status === 200) {
    fieldTable.value = res.data;
    totalField.value = Number(res.count);
  } else {
    ElMessage.error(res.msg);
  }
};

// 查询所有已经添加的字段信息
const queryAllFieldTable = async () => {
  const res = await ledgerTableFieldTabApi({
    page: 1,
    limit: 9999,
    tableId: searchInfoField.tableId
  });

  if (res.status === 200) {
    fieldTableAll.value = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 字段分页大小改变
const handleFieldCurrentChange = async (val: number) => {
  searchInfoField.page = val;
  initFieldTable();
};

// 筛选穿梭框
const filterMethod = (query: string, item: TransferDataItem) => {
  return item.fieldName.toLowerCase().includes(query.toLowerCase());
};

// 删除一个字段
const removeField = (row) => {
  ElMessageBox.confirm('是否确定删除该字段?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // const res = await deleteFiledApi(row.id);

      // if (res.status !== 200) {
      //   return ElMessage.error(res.msg);
      // }

      const _res = await ledgerTableFieldDelApi({ id: row.id });

      if (_res.status === 200) {
        ElMessage.success('已删除');
        initFieldTable();
      } else {
        ElMessage.error(_res.msg);
      }
    })
    .catch(() => {});
};

// 编辑字段信息
const editField = (row) => {
  currentFieldRow.value = JSON.parse(JSON.stringify(row));
  showEditField.value = true;
  loadingBtn.value = false;

  if (!currentFieldRow.value.notNull || currentFieldRow.value.notNull === '-') {
    currentFieldRow.value.notNull = '';
  }

  if (!currentFieldRow.value.notSelect) {
    currentFieldRow.value.notSelect = '';
  }
};

// 确定编辑字段
const sureEditField = async () => {
  if (!currentFieldRow.value.notNull || !currentFieldRow.value.notSelect) {
    return ElMessage.error('请选择是否必填与可选选项');
  }

  loadingBtn.value = true;
  const res = await ledgerTableFieldFormApi(currentFieldRow.value);
  loadingBtn.value = false;

  if (res.status === 200) {
    showEditField.value = false;
    initFieldTable();
  } else {
    ElMessage.error(res.msg);
  }
};

// 获取数据源信息
const getDbInfo = async () => {
  const res = await dbInfoListApi();

  if (res.status === 200) {
    dbSelect.value = res.data;

    if (res.data && res.data.length > 0) {
      searchInfo.dbId = res.data[0].id;
      getFieldType(searchInfo.dbId);
      init();
      loadAllTableInfo();
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 获取字段类型
const getFieldType = async (id: string) => {
  const res = await fieldTypeListApi(id);

  if (res.status === 200) {
    fieldTypeSelect.value = res.data;

    if (res.data && res.data.length > 0) {
      ruleForm.fieldType = res.data[0].typeName;
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 读取菜单
const loadMenu = async (disabledArr) => {
  const res = await loadMenuApi({ page: 1, limit: 99999 });
  loadingMenu.value = false;

  if (res.status === 200) {
    if (res.data && res.data.length > 0) {
      menuList.value = res.data;

      res.data.forEach((item) => {
        if (disabledArr.includes(item.rightId)) {
          item.disabled = true;
        } else {
          item.disabled = false;
        }
      });

      menuTreeSelect.value = listToTree(
        res.data.filter((item) => {
          return (
            item.rightIsMeua === '1' &&
            item.rightName !== '系统管理' &&
            item.rightName !== '基础配置管理'
          );
        })
      );
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 读取字段信息
const loadFieldInfo = async () => {
  loadingField.value = true;
  const res = await ledgerFieldTabApi({ page: 1, limit: 9999 });
  loadingField.value = false;

  if (res.status === 200) {
    if (res.data && res.data.length > 0) {
      fieldSelect.value = res.data;
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 字段选中状态改变
const handleSelectionChange = (val) => {
  selectTableField.value = val;
};

// 复制字段
const copyField = () => {
  copyItems.value = selectTableField.value;
  ElMessage.success('已复制');
};

// 粘贴字段
const pasteField = () => {
  ElMessageBox.confirm(`是否确定粘贴到表 ${currentRow.tableName} ? `, '提示', {
    confirmButtonText: '确 定',
    cancelButtonText: '取 消',
    closeOnClickModal: false,
    type: 'warning',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true;
        instance.cancelButtonClass = 'hidden';
        instance.confirmButtonText = '处理中';

        let repeatItems = []; // 重复字段
        let addItems = []; // 没有重复的可添加字段

        copyItems.value.forEach((item) => {
          const obj = fieldTableAll.value.find((item__) => item__.fieldId === item.fieldId);

          if (obj) {
            repeatItems.push(item);
          } else {
            addItems.push(item);
          }
        });

        if (repeatItems.length === copyItems.value.length) {
          ElMessage.warning('已复制的字段均已在此表中，无需重复添加');
          done();
        } else {
          ElMessage.success(
            '重复' + repeatItems.length + '个字段' + '，粘贴' + addItems.length + '个字段'
          );

          const submitPasteFields = [...addItems, ...fieldTableAll.value];

          await sureAddField(
            submitPasteFields.map((item) => item.fieldId),
            2
          );

          done();
        }
      } else {
        done();
      }
    }
  }).then((action) => {});
};

// 列表转换为 🌲
const listToTree = (data) => {
  const map = {};
  const roots = [];

  data.forEach((item) => {
    map[item.rightId] = { ...item, children: [] };
  });

  // 构建树结构
  data.forEach((item) => {
    const node = map[item.rightId];

    if (item.rightParentId === '0') {
      roots.push(node);
    } else {
      const parent = map[item.rightParentId];

      if (parent) {
        parent.children.push(node);
      }
    }
  });

  return roots;
};

// 提交
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const FormTable = {
        dbId: searchInfo.dbId,
        tableDesc: ruleForm.tableDesc,
        tableName: ruleForm.tableName,
        fieldList: [
          {
            fieldName: ruleForm.tableFieldName,
            fieldDesc: ruleForm.tableFieldDesc,
            fieldSize: ruleForm.fieldLength,
            fieldType: ruleForm.fieldType,
            nullFlag: '2',
            primaryKeyFlag: '1'
          },
          {
            fieldName: 'LEDGER_CREATE_USER_ID',
            fieldDesc: '数据创建者UserId',
            fieldSize: '50',
            fieldType: 'varchar',
            nullFlag: '2'
          },
          {
            fieldName: 'RECIVER_ID',
            fieldDesc: '接收人ID',
            fieldSize: '100',
            fieldType: 'varchar',
            nullFlag: '1'
          },
          {
            fieldName: 'TRANSFER_STATUS',
            fieldDesc: '流转状态',
            fieldSize: '20',
            fieldType: 'varchar',
            nullFlag: '1'
          },
          {
            fieldName: 'EXMINE_STATUS',
            fieldDesc: '审核是否完成',
            fieldSize: '20',
            fieldType: 'varchar',
            nullFlag: '1'
          }
        ]
      };

      loadingBtn.value = true;

      const resTable = await addTableApi(FormTable);

      if (resTable.status !== 200) {
        loadingBtn.value = false;
        return ElMessage.error(resTable.msg);
      } else {
        ruleForm.id = resTable.data;
      }

      ruleForm.menuName = menuList.value.find((item) => item.rightId === ruleForm.menuId).rightName;
      ruleForm.menuUrl = menuList.value.find((item) => item.rightId === ruleForm.menuId).rightUrl;
      ruleForm.dbId = searchInfo.dbId;
      ruleForm.dbName = dbSelect.value.find((item) => item.id === searchInfo.dbId).dbName;

      const res = await ledgerTableFormApi(ruleForm);

      loadingBtn.value = false;

      if (res.status === 200) {
        ElMessage.success('操作成功');
        showDialog.value = false;
        reloadTable(1);
      } else {
        ElMessage.error(res.msg);
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

// 修改绑定的菜单
const sureChangeMenu = async () => {
  if (!currentMenuId.value) return ElMessage.error('未选择模块信息');

  loadingBtn.value = true;

  let __submit = JSON.parse(JSON.stringify(currentRow));

  __submit.menuId = currentMenuId.value;
  __submit.menuName = menuList.value.find((item) => item.rightId === __submit.menuId).rightName;
  __submit.menuUrl = menuList.value.find((item) => item.rightId === __submit.menuId).rightUrl;

  const res = await ledgerTableFormApi(__submit);

  loadingBtn.value = false;

  if (res.status === 200) {
    ElMessage.success('操作成功');
    showBindMenu.value = false;
    reloadTable(1);
    loadAllTableInfo();
  } else {
    ElMessage.error(res.msg);
  }
};

// 添加字段
const addField = () => {
  showAddField.value = true;
  selectedField.value = [];
  loadingBtn.value = false;

  nextTick(() => {
    selectedField.value = fieldTableAll.value.map((item) => item.fieldId);
    selectedField.value.reverse();
  });
};

// 确定添加字段
const sureAddField = async (row, type = 1) => {
  loadingBtn.value = true;

  if (!row) {
    row = selectedField.value;
  }

  let __Form = [];

  for (let i = 0; i < row.length; i++) {
    const __field = fieldSelect.value.find((item) => item.id === row[i]);
    const __fieldTable = fieldTableAll.value.find((item) => item.fieldId === row[i]);

    const __form = {
      fieldName: __field.fieldEname,
      fieldDesc: __field.fieldDesc,
      fieldType: 'varchar',
      fieldSize: '255',
      nullFlag: '2',
      tableId: currentRow.id
    };

    __Form.push({
      fieldId: __field.id,
      fieldDesc: __field.fieldDesc,
      fieldEname: __field.fieldEname,
      fieldName: __field.fieldName,
      fieldShow: __field.fieldShow,
      fieldType: __field.fieldType,
      tableId: currentRow.id,
      notNull: __fieldTable ? __fieldTable.notNull : null,
      notSelect: __fieldTable ? __fieldTable.notSelect : null,
      id: __fieldTable && type === 1 ? __fieldTable.id : $xy.RI()
    });

    if (!__fieldTable) {
      // 字段表中没有的才添加到数据表中
      const resfield = await addFiledApi(__form);

      if (resfield.data) {
        __Form[__Form.length - 1].id = resfield.data;
      }
    }
  }

  const res = await ledgerTableFieldFormListApi(__Form);

  loadingBtn.value = false;

  if (res.status === 200) {
    searchInfoField.page = 1;
    showAddField.value = false;
    initFieldTable();
  } else {
    ElMessage.error(res.msg);
  }
};

searchInfo.tableName = '';
searchInfo.tableDesc = '';
searchInfo.dbId = '';

// 加载所有菜单信息
const loadAllTableInfo = async () => {
  loadingMenu.value = true;

  const res = await ledgerTableTabApi({
    page: 1,
    limit: 99999,
    dbId: searchInfo.dbId
  });

  loadingMenu.value = false;

  if (res.status === 200) {
    allTableInfo.value = res.data;
    const _arr = res.data.map((item) => item.menuId);
    loadMenu(_arr);
  } else {
    ElMessage.error(res.msg);
  }
};

getDbInfo();
loadFieldInfo();
</script>

<style lang="scss" scoped>
:deep(.el-form--inline .el-form-item:nth-child(even)) {
  margin-right: 0;
}
</style>
